'use strict';

const Controller = require('egg').Controller;
const { SuccessModel, FailModel } = require('../resModel/index')

// 引入生成商品id uuid
const { v1 } = require('uuid');
// console.log(uuid.v1())

class GoodsController extends Controller {
  // 1. 查询商品
  async findGoods() {
    console.log('.........:', this.ctx.state)
    const errors = this.app.validator.validate({
      page: {required: false, type: 'string'},
      size: {required: false, type: 'string'}
    }, this.ctx.query)
    if (!errors) {
      const {page, size} = this.ctx.query;
      const res = await this.app.mysql.select('goods', {
        limit: Number(size), // 返回数据量
        offset: page * size, // 数据偏移量
      })
      this.ctx.body = new SuccessModel(res, '查询成功')
    } else {
      this.ctx.body = new FailModel('查询fail')
    }
  }

  // 2. 添加商品
  async addGoods() {
    const errors = this.app.validator.validate({
      skuCount: 'number',
      price: 'string',
      imgUrl: 'string'
    }, this.ctx.request.body)
    if (!errors) {
      const {skuCount, price, imgUrl} = this.ctx.request.body;
      let skuId = v1()
      const goodsInfo = await this.app.mysql.get('goods', { skuId })
      if (!goodsInfo) {
        const insertData = await this.app.mysql.insert('goods', {
          skuId, skuCount, price, imgUrl
        })
        this.ctx.body = new SuccessModel({insertid: insertData.insertId}, '添加成功')
      } else {
        this.ctx.body = new FailModel('数据已经存在')
      }
    } else {
      this.ctx.body = new FailModel(errors, 'fail')
    }
  }
  // 3. 删除商品
  async deleteGoods() {
    // required: true
    const errors = this.app.validator.validate({ id: 'string'}, this.ctx.params)
    console.log('errors', errors)
    const { id } = this.ctx.params;
    const data = await this.app.mysql.delete('goods', {id})
    this.ctx.body = new SuccessModel(data, '删除成功')
  }

  // 4. 修改商品  价钱 / 数量 / 名称
  async updateGoods() {
    const { price, skuCount, imgUrl } = this.ctx.request.body;
    const { id } = this.ctx.params;
    const data = await this.app.mysql.update('goods', {
      id, price, skuCount, imgUrl})
    this.ctx.body = new SuccessModel(data, '修改成功')
  }
}

module.exports = GoodsController;
